import {defineComponent, h, nextTick, PropType, ref, resolveComponent, useTemplateRef, watch} from 'vue';
import {startDrag} from './drag.ts';

export default defineComponent({
  name: 'FxDialog',
  inheritAttrs: false,
  props: {
    // 表单数据
    width: {
      type: String as PropType<string>,
      default: '50%'
    },
    // 字段
    height: {
      type: String as PropType<string>,
      default: '420px'
    },
    // 标签后缀
    title: {
      type: Boolean as PropType<string>,
      default: ''
    },
    // 清除时是否重置
    show: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  emits: [
    'onClose',
    'onUpdateShow'
  ],
  setup(props, context) {
    const {emit, expose} = context;

    const visible = ref(false);
    const dialogRef = useTemplateRef('dialogRef');
    const headerRef = useTemplateRef('headerRef');

    const initDrag = () => {
      if (visible.value) {
        nextTick().then(() => {
          if (!headerRef.value) {
            return;
          }
          if (!dialogRef.value) {
            return;
          }
          if (!dialogRef.value.containerRef) {
            return;
          }
          const $dialog = dialogRef.value.containerRef.querySelector('.basic-dialog');
          const $header = headerRef.value;
          startDrag($header, $dialog);
        });
      }
    };

    const initHeight = () => {
      if (visible.value) {

      }
    };

    watch(() => props.show, (newVal: boolean) => {
      visible.value = newVal;
      initHeight();
      initDrag();
    });

    watch(() => visible.value, (newVal: boolean) => {
      emit('onUpdateShow', newVal);
    });

    return () => {
      // noinspection TypeScriptValidateTypes
      return h(resolveComponent('NModal'), {
        ...context.attrs
      }, {
        header: () => {
          return h('div', {
            class: 'fx-dialog-header',
            style: 'cursor: move'
          }, [
            context.slots.header ?
              context.slots.header()
              : props.title
          ]);
        },
        default: () => {
          return h('div', {
            class: 'fx-dialog-content',
            style: `height:${props.height}`,
          }, [
            h(resolveComponent('NScrollbar'), {
              class: 'fx-dialog-content-scrollbar',
            }, {
              default: () => {
                return context.slots.default?.();
              }
            })
          ]);
        },
        footer: () => context.slots.footer?.(),
        action: () => context.slots.action?.()
      });
    };
  }
});